#include "app_message.h"
#include <stdlib.h>
#include <string.h>
#include "json/cJSON.h"
#include "log/log.h"
#include "app_common.h"


//  字符数组格式： 1 2 4 xxabcd
// json格式: {"conn_type": 1, "id": "5858", "msg": "61626364"}
char *app_message_charsToJson(char *data, int len)
{
    // 1. 从data中解析出conn_type, id_len, msg_len, id, msg
    int conn_type = data[0];
    int id_len = data[1];
    int msg_len = data[2];
    char id[id_len];
    char msg[msg_len];
    memcpy(id, data+3, id_len);
    memcpy(msg, data+3+id_len, msg_len);

    // 2. 将id和msg转换为对应的16进制字符串id_hexstr和msg_hexstr
    char *id_hexstr = app_common_charsToHexstr(id, id_len);
    char *msg_hexstr = app_common_charsToHexstr(msg, msg_len);

    // 3. 根据conn_type, id_hexstr, msg_hexstr生成json字符串
    cJSON * root_obj = cJSON_CreateObject();
    cJSON_AddNumberToObject(root_obj, "conn_type", conn_type);
    cJSON_AddStringToObject(root_obj, "id", id_hexstr);
    cJSON_AddStringToObject(root_obj, "msg", msg_hexstr);
    char *json = cJSON_PrintUnformatted(root_obj);

    // 4. 释放内存
    cJSON_Delete(root_obj);
    free(id_hexstr);
    free(msg_hexstr);

    // 5. 返回json字符串
    return json;
}


//  字符数组格式： 1 2 4 xxabcd
// json格式: {"conn_type": 1, "id": "5858", "msg": "61626364"}
int app_message_jsonToChars(char *json, char *data_buf, int buf_size)
{
    // 1. 解析json，得到conn_type,id_hexstr, msg_hexstr
    cJSON *root_obj = cJSON_Parse(json);
    int conn_type = cJSON_GetObjectItem(root_obj, "conn_type")->valueint;
    char *id_hexstr = cJSON_GetObjectItem(root_obj, "id")->valuestring;
    char *msg_hexstr = cJSON_GetObjectItem(root_obj, "msg")->valuestring;

    // 2. 将id_hexstr和msg_hexstr转换为对应的字符数组id和msg， 同时得到id_len和msg_len
    int id_len;
    int msg_len;
    char *id = app_common_hexstrToChars(id_hexstr, &id_len);
    char *msg = app_common_hexstrToChars(msg_hexstr, &msg_len);

    // 得到字符数组消息的长度
    int len = 3 + id_len + msg_len;
    // 检查缓冲区大小是否足够
    if (buf_size < len) {
        log_error("缓存区大小不够");
        cJSON_Delete(root_obj);
        free(id);
        free(msg);
        return -1;
    }

    // 3. 将conn_type, id_len, msg_len, id, msg写入data_buf中
    data_buf[0] = conn_type;
    data_buf[1] = id_len;
    data_buf[2] = msg_len;
    memcpy(data_buf+3, id, id_len);
    memcpy(data_buf+3+id_len, msg, msg_len);

    // 4. 释放内存
    cJSON_Delete(root_obj);
    free(id);
    free(msg);

    // 5. 返回写入的长度
    return len;
}
